package com.minelx.sqlstructures.core.table;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.minelx.sqlstructures.core.values.FieldValues;
import com.minelx.sqlstructures.statements.Query;

import java.util.List;

import static java.util.stream.Collectors.toList;

public class JsonTable implements ITable {
	public static final String KEY_TABLE_NAME = "name";

	public static final String KEY_FIELDS = "fields";

	private final JSONObject jsonData;

	public JsonTable(JSONObject jsonData) {
		this.jsonData = jsonData;
	}

	@Override
	public JSONArray toJSON(Query query) {
		throw new UnsupportedOperationException("JsonTable.toJSON2 is not implemented yet.");
	}

	@Override
	public void attach(JSONArray lines) {
		throw new UnsupportedOperationException("JsonTable.attach is not implemented yet.");
	}

	@Override
	public FieldValues primary() {
		return getFields().stream()
				.filter(FieldValues::isPrimary)
				.findFirst().orElseThrow(() -> new IllegalStateException("can't find primary key of: " + getName()));
	}

	@Override
	public List<FieldValues> getFields() {
		JSONArray fields = (JSONArray) jsonData.get(KEY_FIELDS);
		return fields.stream().map(field -> (JSONObject) field)
				.map(fieldAsJSON -> new FieldValues(
						fieldAsJSON.getInteger("index"),
						fieldAsJSON.getString("name"),
						fieldAsJSON.getString("type"),
						fieldAsJSON.getString("comment"),
						fieldAsJSON.getBoolean("primary")))
				.collect(toList());
	}

	@Override
	public String getName() {
		return (String) jsonData.get(KEY_TABLE_NAME);
	}

	@Override
	public void clear() {
		throw new UnsupportedOperationException("ITable.clear is not supported.");
	}
}
